package com.xnew.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Word文档工具类
 */
public class WordUtil {

    /**
     * 使用FreeMarker自动生成Word文档
     * @param object   生成Word文档所需要的数据
     * @param fileName  生成Word文档的全路径名称
     */
    public void generateWord(Object object, String fileName, String templatePath, String templateName, HttpServletResponse response) throws Exception {
        // 设置FreeMarker的版本和编码格式
        Configuration configuration = new Configuration(new Version("2.3.28"));
        configuration.setDefaultEncoding("UTF-8");

        // 设置FreeMarker生成Word文档所需要的模板的路径
        configuration.setClassForTemplateLoading(this.getClass(), templatePath);
        // 设置FreeMarker生成Word文档所需要的模板
        Template template = configuration.getTemplate(templateName, "UTF-8");

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String(fileName.toString().getBytes("GBK"), "ISO-8859-1"));
        response.setCharacterEncoding("utf-8");//处理乱码问题
        //生成Word文档
        template.process(object, response.getWriter());


//        // 创建一个Word文档的输出流
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), "UTF-8"));
        //FreeMarker使用Word模板和数据生成Word文档
        template.process(object, out);
        out.flush();
        out.close();
        response.flushBuffer();
    }

}